package com.schooleducation.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.User;
import com.schooleducation.entity.UserRoles;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin/userRoles")
public class UserRolesController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;
	
	/**
	 * 获取用户管理界面
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getPage(HttpSession session, Model model) {
		User admin = (User) session.getAttribute("admin");
		if(admin != null) {
			List<User> users = serviceFac.getUserService().getUserList(0, 10);
			List<UserRoles> urs = serviceFac.getUserService().getUserRolesList();
			
			model.addAttribute("admin", admin);
			model.addAttribute("userList", users);
			model.addAttribute("userRolesList", urs);
			
			
			return "admin/userRoles";
		} else {
			return "redirect:../login";
		}
	}
	
	/**
	 * 更新角色请求提交
	 * @param session
	 * @param data
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String getUpdateUserRoles(HttpSession session, String data) {
		Map<String, Object> state = new HashMap<String, Object>();
		User admin = (User) session.getAttribute("admin");
		if(admin != null) {
			state.put("isLogin", "yes");
			User user = (User) JSONObject.toBean(JSONObject.fromObject(data), User.class);
			if(this.serviceFac.getUserService().updateUserRoles(user)) {
				state.put("update", "success");
			} else {
				state.put("update", "fail");
			}
		} else {
			state.put("isLogin", "no");
		}
		
		return JSONObject.fromObject(state).toString();
	}
}
